package com.app.sysmodule.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http请求
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-2-2
 * Time: 上午9:10
 * To change this template use File | Settings | File Templates.
 */
public class HttpRequestUtil {
    private Logger log = Logger.getLogger(HttpRequestUtil.class);
    private Charset charset = Charset.forName("UTF-8");
    public HttpRequestUtil() {
    }
    private  HttpClientBuilder httpClientBuilder;


    public String req(final HttpRequestBase request)
    {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try
        {
            return httpClient.execute(request,new ResponseHandler<String>()
            {
                
                public String handleResponse(HttpResponse response) throws IOException
                {
                    if (response.getStatusLine().getStatusCode() == 200)
                    {
                        HttpEntity entity = response.getEntity();
                        String content = EntityUtils.toString(entity, charset);
                        EntityUtils.consume(entity);
                        return content;
                    }
                    else
                    {
                        HttpEntity entity = response.getEntity();
                        String content = EntityUtils.toString(entity, charset);
                        EntityUtils.consume(entity);
                        log.error(String.format("WEB请求失败:URL[%s],Method[%s],状态[%s],返回[%s]",request.getURI(),request.getMethod(),response.getStatusLine().getStatusCode(),content));
                        return null;
                    }
                }
            });
        } catch (Exception e) {
            log.error(String.format("WEB请求失败:URL[%s],Method[%s]",request.getURI(),request.getMethod()),e);
            return null;
        } finally {
            request.releaseConnection();
        }
    }

    /**;
     * get请求
     * @param url
     * @return
     */
    public String reqGet(String url,Map<String,String> headers) {
        HttpGet httpGet = new HttpGet(url);
        if(null != headers && headers.size()>0){
            //设置http头
            for(String key:headers.keySet()){
                httpGet.addHeader(key,headers.get(key));
            }
        }
        String result = req(httpGet);
        return result;
    }

    /**
     * post请求
     * @param url
     * @param entity
     * @return
     */
    public String reqPost(String url, HttpEntity entity,Map<String,String> headers) {
        HttpPost httpPost = new HttpPost(url);
        //httpPost.setConfig();
        if (entity != null) {
            httpPost.setEntity(entity);
        }
        String result = req(httpPost);
        return result;
    }

    /**
     * post请求
     * @param url
     * @param param
     * @return
     */
    public JSONObject reqPost(String url, Map<String, Object> param,Map<String,String> headers) throws Exception{
        JSONObject jsonObject = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        if (param != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> map : param.entrySet()) {
                if(null != map.getValue()){
                    nvps.add(new BasicNameValuePair(map.getKey().toString(), map.getValue().toString()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
        }
        if(null != headers && headers.size()>0){
            //设置http头
            for(String key:headers.keySet()){
                httpPost.addHeader(key,headers.get(key));
            }
        }
        String result = req(httpPost);
        log.info(url+"接口返回参数："+result);
        if(StringUtils.isNotEmpty(result)){
            jsonObject = JSONObject.parseObject(result);
        }
        return jsonObject;
    }
    /**
     * post请求
     * @param url
     * @param strParam
     * @return
     */
    public JSONObject reqPost(String url, String strParam,Map<String,String> headers) throws Exception{
        JSONObject jsonObject = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isNotEmpty(strParam)) {
            HttpEntity strEntity = new StringEntity(strParam, charset);
            if (strEntity != null) {
                httpPost.setEntity(strEntity);
            }
        }
        if(null != headers && headers.size()>0){
            //设置http头
            for(String key:headers.keySet()){
                httpPost.addHeader(key,headers.get(key));
            }
        }
//        httpPost.setHeader("Accept", "application/*");
        String result = req(httpPost);
        log.info(url+"接口返回参数："+result);
        if(StringUtils.isNotEmpty(result)){
            jsonObject = JSONObject.parseObject(result);
        }
        return jsonObject;
    }
	public HttpClientBuilder getHttpClientBuilder() {
		return httpClientBuilder;
	}

	public void setHttpClientBuilder(HttpClientBuilder httpClientBuilder) {
		this.httpClientBuilder = httpClientBuilder;
	}


    public JSONObject reqPost(String url, String s) {
        return null;
    }
}
